<template>
	<view>
		<view class="alldiv">
			<view class="headdiv">
				<!-- <web-view v-show="!timeShow && !peopleShow" id="map" class="map" tabindex="0"></web-view> -->
				<!-- <map v-show="!timeShow && !peopleShow" style="width: 100%;height: 100%;" :latitude="latitude" :longitude="longitude" :markers="covers">
        </map> -->
				<cover-image v-show="!timeShow && !peopleShow" class="back" @click="returns"
					src="@/static/image/arrow-left.png"></cover-image>
			</view>
			<view class="bodydiv">
				<!-- 拼车功能暂时隐藏 -->
				<!-- <view class="item">
          <u-icon :customStyle="{ marginRight: 24 + 'rpx' }" :name="icon.carPooling" :size="54"></u-icon>
          <view class="content">
            <text class="title van-ellipsis">{{ language.FreeRide.carPooling }}</text>
            <text class="van-ellipsis">{{ language.FreeRide.carPoolingTip }}</text>
          </view>
          <view class="option">
            <view class="text">
              <text class="van-ellipsis">
                {{ language.FreeRide.carPoolingTextTip1 }}
                <span class="green">{{ carPoolingNum }}</span>
                {{ language.FreeRide.carPoolingTextTip2 }}
              </text>
              <text class="van-ellipsis">
                {{ language.FreeRide.carPoolingTextTip3 }}
                <span>{{ exclusiveNum }}</span>
                {{ language.FreeRide.carPoolingTextTip2 }}
              </text>
            </view>
            <u-checkbox-group v-model="checked" :disabled="checked.indexOf('carPooling') !== -1">
              <u-checkbox activeColor="rgba(47, 212, 184, 1)" name="carPooling"></u-checkbox>
            </u-checkbox-group>
          </view>
        </view> -->
				<view class="item">
					<u-icon :customStyle="{ marginRight: 24 + 'rpx' }" :name="icon.exclusive" :size="54"></u-icon>
					<view class="content">
						<text class="title van-ellipsis">{{ language.FreeRide.exclusive }}</text>
						<text class="van-ellipsis">{{ language.FreeRide.exclusiveTip }}</text>
					</view>
					<view class="option">
						<view class="text">
							<text class="van-ellipsis">
								{{ language.FreeRide.exclusiveTextTip1 }}
								<span class="green">{{ exclusiveNum }}</span>
								{{ language.FreeRide.carPoolingTextTip2 }}
							</text>
						</view>
						<u-checkbox-group v-model="checked">
							<u-checkbox activeColor="rgba(47, 212, 184, 1)" name="exclusive"
								:disabled="checked.indexOf('exclusive') !== -1"></u-checkbox>
						</u-checkbox-group>
					</view>
				</view>
				<view class="bottomdiv">
					<view class="info">
						<!-- 人数选择 -->
						<view class="info-div" @click="onPeopleTime">
							{{ peopleNum }} {{ language.FreeRide.people }}
							<u-icon class="arrow" name="arrow-right" color="rgba(153, 153, 153, 1)" size="14"></u-icon>
						</view>
						<!-- 时间选择 -->
						<view class="info-div" @click="onSelectTime">
							{{ appointDate }} {{ appointStartTime }} ~ {{ appointEndTime }}
							<u-icon class="arrow" name="arrow-right" color="rgba(153, 153, 153, 1)" size="14"></u-icon>
						</view>
					</view>
					<u-button class="button" :text="language.FreeRide.yysfc" shape="circle"
						color="linear-gradient(90deg, rgba(65, 240, 135, 1) 0%, rgba(47, 212, 184, 1) 100%)"
						@click="goNext"></u-button>
				</view>
			</view>
		</view>
		<!-- 选择时间 -->
		<u-popup :show="timeShow" mode="bottom" closeable round="20" @close="timeShow = false">
			<view class="popup-div">
				<text class="popup-title">{{ language.FreeRide.xzcfsj }}</text>
				<text class="popup-sub-title">{{ language.FreeRide.rstx }}</text>
				<view class="select-time">
					<view class="select-time-item" :class="{'select-time-item-active': timeType === 'start'}"
						@click="changeTimeType('start')">
						<text class="title">{{ language.FreeRide.zzcfsj }}</text>
						<text>{{ currentDay }}{{ showStartTime }}</text>
					</view>
					<view class="select-time-item" :class="{'select-time-item-active': timeType === 'end'}"
						@click="changeTimeType('end')">
						<text class="title">{{ language.FreeRide.zwcfsj }}</text>
						<text>{{ currentDay }}{{ showEndTime }}</text>
					</view>
				</view>
				<u-picker :show="timeShow" ref="timePicker" :columns="timeColumns" :showToolbar="false"
					:visibleItemCount="4" @change="timeHandler"></u-picker>
				<u-button class="button" shape="circle"
					color="linear-gradient(90deg, rgba(65, 240, 135, 1) 0%, rgba(47, 212, 184, 1) 100%)"
					@click="okTime">
					<view style="font-size: 16px;margin-bottom: 4px;">{{ language.FreeRide.confirm }}</view>
					<view style="font-size: 14px;">{{ currentDay }}{{ showStartTime }} -
						{{ showEndTime }}{{ language.FreeRide.go }}
					</view>
				</u-button>
			</view>
		</u-popup>
		<!-- 选择人数 -->
		<u-popup :show="peopleShow" mode="bottom" closeable round="20" @close="peopleShow = false">
			<view class="popup-div">
				<text class="popup-title">{{ language.FreeRide.xzczrs }}</text>
				<text class="popup-sub-title">{{ language.FreeRide.rstx }}</text>
				<view class="select-people">
					<view v-for="i in 4" :key="i" class="select-people-item"
						:class="{'select-people-item-active': selctPeopleNum === i}" @click="selctPeopleNum = i">
						<text class="text">{{ i }}{{ language.FreeRide.people }}</text>
					</view>
				</view>
				<u-button class="button"
					:text="language.FreeRide.confirm + selctPeopleNum + language.FreeRide.people + language.FreeRide.ride"
					shape="circle" color="linear-gradient(90deg, rgba(65, 240, 135, 1) 0%, rgba(47, 212, 184, 1) 100%)"
					@click="okPeople" />
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		getInquiryprice,
		createOnlineCarOrder
	} from '@/api/driver.js'
	export default {
		name: 'freeRideNow',
		data() {
			return {
				language: {},
				icon: {
					// 拼车
					carPooling: require('@/static/image/carPooling.png'),
					// 独享
					exclusive: require('@/static/image/exclusive.png'),
				},
				carPoolingNum: 9.33, // 拼成一口价
				exclusiveNum: null, // 独享价
				checked: ['exclusive'],
				peopleNum: 1,
				appointDate: '',
				appointStartTime: '',
				appointEndTime: '',
				// 时间选择弹窗
				allHour: [],
				allMin: [],
				timeDay: [], // 天选择项
				timeColumns: [
					[],
					[],
					[]
				],
				timeShow: false, // 时间选择器
				timeType: 'start',
				currentDay: '', // 记录的是文字
				startTime: [], // 记录的是index
				endTime: [], // 记录的是index
				// 乘坐人数选择
				peopleShow: false,
				selctPeopleNum: 1,
				distance: null,
				startPointObj: {},
				endPointObj: {}
			}
		},
		computed: {
			showStartTime() {
				let str = '';
				if (String(this.startTime[0]).length) {
					let hourText0 = this.timeColumns[1][this.startTime[0]]
					str = (String(parseInt(hourText0)).length === 1 ? '0' + parseInt(hourText0) : parseInt(hourText0)) +
						':'
				}
				if (String(this.startTime[1]).length) {
					let hourText1 = this.timeColumns[2][this.startTime[1]]
					str += String(parseInt(hourText1)).length === 1 ? '0' + parseInt(hourText1) : parseInt(hourText1)
				}
				return str
			},
			showEndTime() {
				let str = ''
				if (String(this.endTime[0]).length) {
					let hourText0 = this.timeColumns[1][this.endTime[0]]
					str = (String(parseInt(hourText0)).length === 1 ? '0' + parseInt(hourText0) : parseInt(hourText0)) +
						':'
				}
				if (String(this.endTime[1]).length) {
					let hourText1 = this.timeColumns[2][this.endTime[1]]
					str += String(parseInt(hourText1)).length === 1 ? '0' + parseInt(hourText1) : parseInt(hourText1)
				}
				return str
			}
		},
		async onLoad(option) {
			if (!option.startPlace || !option.endPlace || !option.distance) {
				uni.redirectTo({
					url: "/pages/Home/freeRide/index1",
				});
			}
			this.startPointObj = {
				address: option.startPlace,
				latitude: option.startLatitude,
				longitude: option.startLongitude
			}
			this.endPointObj = {
				address: option.endPlace,
				latitude: option.endLatitude,
				longitude: option.endLongitude
			}
			this.distance = option.distance
			console.log('distance', this.distance)
			try {
				getInquiryprice({
					distance: this.distance
				}).then(res => {
					if (res.code === 0) {
						this.exclusiveNum = res.data
					}
				})
			} catch {
				console.log('获取价格失败')
			}
			this.getlanguagedata();
			this.allHour = []
			for (let i = 0; i <= 23; i++) {
				this.allHour.push(i + this.language.FreeRide.d)
			}
			this.allMin = []
			for (let i = 0; i <= 55;) {
				this.allMin.push((String(i).length === 1 ? '0' + i : i) + this.language.FreeRide.min);
				i += 5;
			}
			this.onSelectTime();
		},
		onShow: function() {
			this.getlanguagedata();
		},
		methods: {
			returns() {
				uni.redirectTo({
					url: `/pages/Home/freeRide/index1`
				});
				// uni.redirectTo({
				// 	url: `/pages/Home/freeRide/index1?startPlace=${
        //   this.startPointObj.address}&startLongitude=${
        //   this.startPointObj.longitude}&startLatitude=${
        //   this.startPointObj.latitude}`
				// });
			},
			goNext() {
				if (!this.exclusiveNum) return
				if (new Date().getTime() >= new Date(this.formatDate(this.appointEndTime)).getTime()) {
					// 最晚结束时间早于当前时间
					uni.showToast({
						title: this.language.FreeRide.zwcfsjbnzydqsj,
						icon: 'none',
						duration: 2000
					});
					return
				}
				const data = {
					planStartTime: this.formatDate(this.appointStartTime),
					startPlace: this.startPointObj.address,
					startLongitude: this.startPointObj.longitude,
					startLatitude: this.startPointObj.latitude,
					planEndTime: this.formatDate(this.appointEndTime),
					endPlace: this.endPointObj.address,
					endLongitude: this.endPointObj.longitude,
					endLatitude: this.endPointObj.latitude,
					distance: this.distance,
					cost: this.exclusiveNum,
					// orderType: 1, // 订单类型（1顺风车 2网约车）
					userId: uni.getStorageSync('UID'),
					passengers: this.peopleNum
				}
				uni.showLoading({
					title: 'loading...'
				});
				createOnlineCarOrder(data).then(res => {
					if (res.code === 0) {
						uni.hideLoading();
						uni.redirectTo({
							url: "/pages/Home/freeRide/waitOrder?id=" + res.data,
						});
					}
				}).catch(res => {
					console.log(res)
					uni.hideLoading();
				})
			},
			formatDate(time) {
				const date = new Date();
				const dayIndex = this.timeDay.findIndex(d => d === this.appointDate)
				date.setDate(date.getDate() + dayIndex);

				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1，并确保两位数
				const day = String(date.getDate()).padStart(2, '0');

				return `${year}-${month}-${day} ${time}:00`;
			},
			getlanguagedata() {
				this.language =
					this.$store.getters["internationalization/getinternationalization"];
				this.timeDay = this.language.FreeRide.timeList
			},
			// 时间选择
			onSelectTime() {
				this.$refs.timePicker?.setColumnValues(0, this.timeDay)
				this.timeColumns[0] = this.timeDay;

				// this.$refs.timePicker?.setColumnValues(1, hour)
				this.timeColumns[1] = [...this.allHour];

				// this.$refs.timePicker?.setColumnValues(2, min)
				this.timeColumns[2] = [...this.allMin];
				if (!this.appointDate) {
					// 没有选择过时间
					this.appointDate = this.timeDay[0]
					const index = this.timeDay.findIndex(d => d === this.appointDate)
					this.currentDay = this.timeDay[index !== -1 ? index : 0]

					const now = new Date();
					const currentHour = now.getHours();
					const currentMin = now.getMinutes();
					const minIndx = this.allMin.findIndex(d => parseInt(d) > Number(currentMin))
					this.startTime = [currentHour, minIndx !== -1 ? minIndx : this.allMin.length - 1]
					this.initShowTime()
					this.$nextTick(() => {
						this.appointStartTime = this.showStartTime
						this.appointEndTime = this.showEndTime
					})
				}
				this.timeShow = true
				this.$nextTick(() => {
					this.initTimePicker()
				})
			},
			// 初始化时间选择绑定的值
			initShowTime(onlyChange = true) {
				if (onlyChange) {
					const endHourIndex = (this.startTime[0] !== this.timeColumns[1].length - 1 && (this.startTime[1] + 3) >
						this.timeColumns[2].length - 1) ? this.startTime[0] + 1 : this.startTime[0]
					let endMinIndex = this.startTime[1] + 3
					if (endHourIndex !== this.startTime[0]) {
						// 跨时
						endMinIndex = endMinIndex - (this.timeColumns[2].length - 1)
					} else if ((this.startTime[1] + 3) > this.timeColumns[2].length - 1) {
						// 最后一小时处理
						endMinIndex = this.timeColumns[2].length - 1
					}
					this.endTime = [endHourIndex, endMinIndex]
				}
			},
			// 初始化时间选择器
			initTimePicker(timeIndex = []) {
				if (timeIndex?.length === 3) {
					this.$refs.timePicker?.setIndexs(timeIndex)
				} else {
					const day = this.timeColumns[0].findIndex(d => d === this.currentDay)
					if (this.timeType === 'start') {
						timeIndex = [day === -1 ? 0 : day, this.startTime[0], this.startTime[1]]
					} else {
						timeIndex = [day === -1 ? 0 : day, this.endTime[0], this.endTime[1]]
					}
					this.$refs.timePicker?.setIndexs(timeIndex)
				}
			},
			changeTimeType(type) {
				this.timeType = type;
				this.initTimePicker()
			},
			timeHandler(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					this.currentDay = this.timeColumns[0][index]
				} else if (columnIndex === 1) {
					if (this.timeType === 'start') {
						this.$set(this.startTime, 0, index)
						this.initShowTime()
					} else {
						this.$set(this.endTime, 0, index)
					}
				} else if (columnIndex === 2) {
					if (this.timeType === 'start') {
						this.$set(this.startTime, 1, index)
						this.initShowTime()
					} else {
						this.$set(this.endTime, 1, index)
					}
				}
			},
			okTime() {
				if ((this.startTime[0] > this.endTime[0]) || (this.startTime[0] === this.endTime[0] && this.startTime[1] >
						this.endTime[1])) {
					uni.showToast({
						title: this.language.FreeRide.zwcfsjbnzyzzcfsj,
						icon: 'none',
						duration: 2000
					});
					return
				}
				this.appointDate = this.currentDay;
				this.appointStartTime = this.showStartTime;
				this.appointEndTime = this.showEndTime;
				this.timeShow = false
			},
			okPeople() {
				this.peopleNum = this.selctPeopleNum;
				this.peopleShow = false;
			},
			// 人数选择
			onPeopleTime() {
				this.peopleShow = true;
			},
		}
	}
</script>

<style lang="less" scoped>
	.alldiv {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.headdiv {
			position: relative;
			width: 100%;
			overflow: hidden;
			flex: 1;

			.map {
				// 隐藏选中时的div边框
				width: calc(100% + 4px);
				height: calc(100% + 4px);
				outline: none;
				margin: -2px 0 0 -2px;
			}

			.back {
				position: absolute;
				top: calc(var(--status-bar-height) + 6rpx);
				left: 0;
				width: 80rpx;
				height: 60rpx;
			}
		}

		.bodydiv {
			max-height: 60vh;
			overflow-y: auto;
			box-shadow: 0px -3px 6px rgba(6, 145, 161, 0.05);
			border-radius: 20px 20px 0 0;
			padding: 4px 0 24px 0;
			background-color: #fff;

			.item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20px 16px 12px 16px;
			}

			.item+.item {
				border-top: 1px solid rgba(217, 219, 218, 1);
			}

			.content {
				font-size: 10px;
				color: rgba(153, 153, 153, 1);
				line-height: 1.5;
				margin-right: 16px;

				.title {
					font-size: 16px;
					color: rgba(56, 56, 56, 1);
					font-weight: 700;
					display: block;
				}
			}

			.option {
				flex: 1;
				text-align: right;
				display: flex;
				justify-content: end;

				.text {
					margin-right: 12px;
					color: rgba(51, 51, 51, 1);
					font-size: 10px;
					line-height: 1.4;

					.van-ellipsis {
						display: block;
					}
				}

				.green {
					font-size: 18px;
					color: rgba(47, 212, 184, 1);
					padding: 0 2px;
				}

				::v-deep {
					.u-checkbox__icon-wrap {
						margin-right: 0;
					}

					.u-checkbox__icon-wrap--disabled--checked {
						color: rgba(255, 255, 255, 1) !important;
						background-color: rgba(47, 212, 184, 1) !important;
						border-color: rgb(47, 212, 184) !important;

						.u-icon__icon {
							color: #fff !important;
						}
					}
				}
			}

			.bottomdiv {
				padding: 0 16px;
				border-radius: 20px 20px 0px 0px;
				box-shadow: 0px -3px 6px rgba(6, 145, 161, 0.05);

				.info {
					display: flex;
					align-items: center;
					height: 56px;

					.info-div {
						flex: 1;
						flex-shrink: 0;
						line-height: 1;
						text-align: center;
						font-size: 14px;

						&:first-child {
							border-right: 1px solid rgba(217, 219, 218, 1);
							padding-right: 16px;
						}

						.arrow {
							float: right;
						}
					}
				}
			}
		}
	}

	.popup-div {
		padding: 24px 16px;

		.popup-title {
			font-size: 16px;
			color: rgba(56, 56, 56, 1);
			line-height: 1.4;
			margin-bottom: 4px;
			font-weight: 700;
			display: block;
		}

		.popup-sub-title {
			font-size: 10px;
			line-height: 1.4;
			color: rgba(153, 153, 153, 1);
			display: block;
		}

		.select-time {
			display: flex;
			align-items: center;
			margin-top: 16px;
			border-radius: 12px;
			overflow: hidden;

			.select-time-item {
				position: relative;
				flex: 1;
				flex-shrink: 0;
				color: rgba(51, 51, 51, 1);
				font-size: 10px;
				text-align: center;
				padding: 16px 0;

				&:first-child {
					&::after {
						position: absolute;
						content: '';
						top: 17px;
						bottom: 17px;
						right: 0;
						width: 1px;
						background-color: rgba(217, 219, 218, 1);
					}
				}

				.title {
					font-size: 14px;
					line-height: 20px;
					display: block;
				}
			}

			.select-time-item-active {
				background: rgba(250, 251, 253, 1);
				color: rgba(47, 212, 184, 1);
			}
		}

		.select-people {
			display: flex;
			justify-content: space-between;
			margin-top: 24px;

			.select-people-item {
				position: relative;
				flex: 1;
				flex-shrink: 0;
				margin-right: 5%;
				border-radius: 12px;
				box-shadow: 0px 2px 4px rgba(5, 48, 7, 0.08);
				text-align: center;
				font-size: 14px;
				font-weight: 700;
				color: rgba(51, 51, 51, 1);
				border: 1px solid transparent;

				&:last-child {
					margin-right: 0;
				}

				.text {
					line-height: 60px;
				}
			}

			.select-people-item-active {
				color: rgba(47, 212, 184, 1);
				border-color: rgba(47, 212, 184, 1);
			}
		}

		.button {
			margin: 24px auto 0 auto;
			flex-direction: column;
			font-weight: 700;
			line-height: 1;
		}

		::v-deep {
			.u-fade-enter-active {
				display: none !important;
				;
			}

			.u-slide-up-enter-active {
				position: relative !important;
			}
		}
	}

	.button {
		height: 44px;
		width: 90%;
		margin: 0 auto;

		::v-deep {
			.u-button__text {
				font-size: 16px !important;
			}
		}
	}
</style>